package com.example.vueback.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Map;


@Slf4j
public class JwtUtils {

    private static final String SIGN = "Y*(GY*9YT0F*&*(";

   public static String createToken(Map<String, String> map) {
       //1.设置过期时间
       Calendar calendar = Calendar.getInstance();
       calendar.add(Calendar.MINUTE, 30);
       //2.创建 jwt builder， 添加自定义载荷
       JWTCreator.Builder builder = JWT.create();
       for(Map.Entry<String, String> entry: map.entrySet()) {
            builder.withClaim(entry.getKey(), entry.getValue());
       }
       //3.生成 Token
       String token = builder.withExpiresAt(calendar.getTime())
               .sign(Algorithm.HMAC256(SIGN));
       return token;
   }

   public static boolean checkToken(String token) {
       try {
            JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
            return true;
       } catch (Exception e) {
            log.error("校验时发现 JWT 非法!");
            e.printStackTrace();
            return false;
       }
   }

}
